package com.clayecloud.module_main.ui.fragment;

import android.animation.ObjectAnimator;
import android.animation.StateListAnimator;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.clayecloud.lib_common.room.ClientDataBase;
import com.clayecloud.lib_common.room.entity.ClientBase;
import com.clayecloud.lib_common.room.entity.ClientUser;
import com.clayecloud.lib_common.utils.LoginUtil;
import com.clayecloud.module_main.R;
import com.clayecloud.module_main.databinding.FragmentMeBinding;
import com.clayecloud.module_main.viewModels.FragmentMeViewModel;
import com.gyf.immersionbar.ImmersionBar;

import io.reactivex.disposables.Disposable;

public class MeFragment extends Fragment {

    private FragmentMeBinding fragmentMeBinding;
    private FragmentMeViewModel fragmentMeViewModel;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        fragmentMeBinding =  DataBindingUtil.inflate(inflater, R.layout.fragment_me,container,false);
        ViewModelProvider.Factory factory = ViewModelProvider.AndroidViewModelFactory.getInstance(getActivity().getApplication());
        ViewModelProvider viewModelProvider = new ViewModelProvider(this,factory);
        fragmentMeViewModel = viewModelProvider.get(FragmentMeViewModel.class);

        //初始化数据
        fragmentMeViewModel.loadData();
        fragmentMeBinding.setModel(fragmentMeViewModel);

        //弹性滑动
        fragmentMeBinding.smartRefreshLayout.setEnableRefresh(false);//是否启用下拉刷新功能
        fragmentMeBinding.smartRefreshLayout.setEnableLoadMore(false);//是否启用上拉加载功能
        fragmentMeBinding.smartRefreshLayout.setEnablePureScrollMode(true);//是否启用纯滚动模式
        fragmentMeBinding.smartRefreshLayout.setEnableOverScrollBounce(true);//是否启用越界回弹
        fragmentMeBinding.smartRefreshLayout.setEnableOverScrollDrag(true);//是否启用越界拖动（仿苹果效果）1.0.4

        //设置AppBarLayout的高程（原始的设置方式已经被弃用）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            StateListAnimator stateListAnimator = new StateListAnimator();
            stateListAnimator.addState(new int[0], ObjectAnimator.ofFloat(fragmentMeBinding.appBarLayout, "elevation", 0.1f));
            fragmentMeBinding.appBarLayout.setStateListAnimator(stateListAnimator);
        }

        // 滑动监听
        fragmentMeBinding.nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                // 上滑改变透明度的变化
                if (scrollY <= 230){
                    fragmentMeBinding.titleBarFrame.setBackgroundColor(Color.argb(scrollY,255,255,255));
                    fragmentMeBinding.title.setTextColor(Color.argb(scrollY,48,49,51));
                }
            }
        });

        // 显示圆形的头像
        loadAvatar("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201807%2F30%2F20180730233008_nukZn.thumb.700_0.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640685672&t=5f9e6ad243a1ae75d28525e1d2372250");

        //判断用户状态
        ClientDataBase.getClientDataBaseInstance().getClientBaseService().getClientBaseById(1).observe(this, new Observer<ClientBase>() {
            @Override
            public void onChanged(ClientBase clientBase) {
                if(clientBase == null){
                    return;
                }
                if(clientBase.getUserID() == 0){
                    //未登录
                    fragmentMeBinding.username.setText("未登录");
                    fragmentMeBinding.logininfo.setText("登录我的 * * 社区一账通 ");
                    fragmentMeBinding.title.setText("未登录");
                    loadAvatar("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201807%2F30%2F20180730233008_nukZn.thumb.700_0.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640685672&t=5f9e6ad243a1ae75d28525e1d2372250");
                }else{
                    //已登录
                    fragmentMeBinding.username.setText(LoginUtil.getUserBaseinfo().getUserName());
                    fragmentMeBinding.logininfo.setText("管理我的社区账号");
                    fragmentMeBinding.title.setText(LoginUtil.getUserBaseinfo().getUserName());
                    loadAvatar(LoginUtil.getUserBaseinfo().getUserAvatar());
                }
            }
        });

        return fragmentMeBinding.getRoot();
    }


    /**
     * 加载头像
     * @param url
     */
    private void loadAvatar(String url){
        Glide.with(getContext())
                .load( url)
                .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                .into(fragmentMeBinding.appCompatImageView);
    }

    /**
     * 用来处理创建除view的所有东西
     * @param savedInstanceState
     */
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //沉浸式状态栏
        ImmersionBar.with(this).statusBarDarkFont(true).init();
    }

    /**
     * 在删除此fragment时 进行操作防止内存泄漏
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        // 必须调用该方法，防止内存泄漏
        ImmersionBar.destroy(this);
    }

}
